﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PookSistener.Customer
{
    public partial class frmCustomer : Form
    {
        OleDbConnection conn = null;

        string MODE = "";

        List<Customer> customers = new List<Customer>();

        public frmCustomer()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            MODE = "ADD";

            panel1.Visible = true;
            panel1.Left = this.Left + 10;
            panel1.Top = this.Top + 10;
            panel1.Width = this.Width - 10;
            panel1.Height = this.Height - 10;

            ClearData();
        }

        private void ClearData()
        {
            txtCustomerName.Text = "";
            txtPhone.Text = "";
            txtAddress.Text = "";
            txtCustomerName.Focus();
            txtCustomerName.SelectAll();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                if (dataGridView1.SelectedRows.Count > 0)
                {
                    MODE = "EDIT";
                    DataGridViewRow row = dataGridView1.SelectedRows[0];

                    txtCustomerId.Text = row.Cells["ID"].Value.ToString();
                    txtCustomerName.Text = row.Cells["tName"].Value.ToString();
                    txtPhone.Text = row.Cells["Phone"].Value.ToString();
                    txtAddress.Text = row.Cells["Address"].Value.ToString();

                    panel1.Visible = true;
                    panel1.Left = this.Left + 10;
                    panel1.Top = this.Top + 10;
                    panel1.Width = this.Width - 10;
                    panel1.Height = this.Height - 10;
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                if(dataGridView1.SelectedRows.Count > 0)
                {
                    if (DialogResult.Yes == MessageBox.Show("คุณต้องการลบข้อมูลนี้ใช่หรือไม่", "คำยืนยัน", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    {

                        DataGridViewRow row = dataGridView1.SelectedRows[0];

                        try
                        {
                            int customer_id = Convert.ToInt32(row.Cells["ID"].Value);

                            string sql = "DELETE FROM Customer WHERE ID=@ID";

                            OleDbCommand cmd = new OleDbCommand();
                            cmd.CommandText = sql;
                            cmd.CommandType = CommandType.Text;
                            cmd.Connection = conn;
                            cmd.Parameters.Clear();

                            cmd.Parameters.Add("@ID", OleDbType.Integer).Value = customer_id;

                            cmd.ExecuteNonQuery();

                            MessageBox.Show("ลบข้อมูลเรียบร้อยแล้ว");

                            ListAllCustomer();

                            dataGridView1.DataSource = null;
                            dataGridView1.DataSource = customers;
                            dataGridView1.Invalidate();
                            
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error : " + ex.Message);
                        }
                    }
                }
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {

            if (txtFilter.Text.Trim().Length == 0)
            {
                dataGridView1.DataSource = customers;
                dataGridView1.Invalidate();
            }
            else
            {
                List<Customer> filter = new List<Customer>();

                for (int i = 0; i < customers.Count; i++)
                {
                    if (customers[i].Name.IndexOf(txtFilter.Text) != -1)
                    {
                        filter.Add(customers[i]);
                        continue;
                    }

                    if (customers[i].Phone.IndexOf(txtFilter.Text) != -1)
                    {
                        filter.Add(customers[i]);
                        continue;
                    }
                }

                dataGridView1.DataSource = filter;
                dataGridView1.Invalidate();
            }
        }

        private void ListAllCustomer()
        {
            customers.Clear();
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM Customer ORDER BY ID", conn);
            OleDbDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                Customer item = new Customer();
                item.ID = reader.GetInt32(0);
                item.Name = reader.GetString(1);
                item.Phone = reader.GetString(2);
                item.Address = reader.GetString(3);

                customers.Add(item);
            }

            reader.Close();
        }

        private void frmCustomerList_Load(object sender, EventArgs e)
        {
            conn = new OleDbConnection(PookSistener.Properties.Settings.Default.DatabaseConnectionString);
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
            conn.Open();

            ListAllCustomer();

            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = customers;
            dataGridView1.Invalidate();

            dataGridView1_Click(null, null);
        }

        private void txtFilter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSearch_Click(null, null);
            }
        }

        private void cmdClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            panel1.Visible = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (txtCustomerName.Text.Trim().Length > 0)
            {
                if (MODE.Equals("ADD"))
                {
                    string sql = @"INSERT INTO Customer(Name, Phone, Address) VALUES(@Name, @Phone, @Address)";
                    OleDbCommand cmd = new OleDbCommand();
                    cmd.CommandText = sql;
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = conn;
                    cmd.Parameters.Clear();

                    cmd.Parameters.Add("@Name", OleDbType.VarChar).Value = txtCustomerName.Text;
                    cmd.Parameters.Add("@Phoen", OleDbType.VarChar).Value = txtPhone.Text;
                    cmd.Parameters.Add("@Address", OleDbType.VarChar).Value = txtAddress.Text;

                    cmd.ExecuteNonQuery();

                    MessageBox.Show("เพิ่มข้อมูลเรียบร้อยแล้ว");
                    ClearData();

                    panel1.Visible = false;

                    ListAllCustomer();

                    dataGridView1.AutoGenerateColumns = false;
                    dataGridView1.DataSource = null;
                    dataGridView1.DataSource = customers;
                    dataGridView1.Invalidate();
                }
                else if (MODE.Equals("EDIT"))
                {
                    try
                    {
                        int customer_id = Convert.ToInt32(txtCustomerId.Text);

                        string sql = @"UPDATE Customer SET Name=@Name, Phone=@Phone, Address=@Address WHERE ID=@ID";

                        OleDbCommand cmd = new OleDbCommand();
                        cmd.CommandText = sql;
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = conn;
                        cmd.Parameters.Clear();

                        cmd.Parameters.Add("@Name", OleDbType.VarChar).Value = txtCustomerName.Text;
                        cmd.Parameters.Add("@Phoen", OleDbType.VarChar).Value = txtPhone.Text;
                        cmd.Parameters.Add("@Address", OleDbType.VarChar).Value = txtAddress.Text;
                        cmd.Parameters.Add("@ID", OleDbType.Integer).Value = txtCustomerId.Text;

                        cmd.ExecuteNonQuery();


                        MessageBox.Show("แก้ไขข้อมูลเรียบร้อยแล้ว");

                        panel1.Visible = false;

                        ListAllCustomer();

                        dataGridView1.AutoGenerateColumns = false;
                        dataGridView1.DataSource = null;
                        dataGridView1.DataSource = customers;
                        dataGridView1.Invalidate();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("เกิดปัญหาบางอย่างขึ้น [" + ex.Message + "]");
                    }
                }
            }
        }

        private void dataGridView1_Resize(object sender, EventArgs e)
        {
            int scrollBarWidth = SystemInformation.VerticalScrollBarWidth + 5;
            int rowHeaderWidth = dataGridView1.RowHeadersWidth + 3;

            int width = dataGridView1.Width - scrollBarWidth;

            int remainingWidth = (int)(width / 2);

            dataGridView1.Columns["tName"].Width = (width - remainingWidth);
            dataGridView1.Columns["Phone"].Width = (remainingWidth);
        }

        private void dataGridView1_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection rows = dataGridView1.SelectedRows;
            if (rows.Count > 0)
            {
                btnEdit.Enabled = true;
                btnDelete.Enabled = true;
                button3.Enabled = true;
            }
            else
            {
                btnEdit.Enabled = false;
                btnDelete.Enabled = false;
                button3.Enabled = false;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection rows = dataGridView1.SelectedRows;
            if (rows.Count > 0)
            {
                DataGridViewRow row = rows[0];

                frmCustomerProduct frm = new frmCustomerProduct();
                frm.txtCustomerName.Text = row.Cells["tName"].Value.ToString();
                frm.txtCustomerName.Tag = row.Cells["ID"].Value;
                frm.ShowDialog();
                frm.Height = frm.Height + 1;
            }
        }
    }
}
